const express = require('express');
const router = express.Router();
const {
  Strategy,
  LocalTour,
  FreeTour,
  GroupTour,
  Hotel,
  VisaService
} = require('../models/Travel');

// ==================== 攻略相关 API ====================

// 获取所有攻略
router.get('/strategies', async (req, res) => {
  try {
    const { page = 1, limit = 10, destination, difficulty } = req.query;
    const query = {};
    
    if (destination) query.destination = new RegExp(destination, 'i');
    if (difficulty) query.difficulty = difficulty;

    const strategies = await Strategy.find(query)
      .populate('author', 'name username avatar')
      .sort({ createdAt: -1 })
      .limit(limit * 1)
      .skip((page - 1) * limit);

    const total = await Strategy.countDocuments(query);

    res.json({
      success: true,
      data: {
        strategies,
        totalPages: Math.ceil(total / limit),
        currentPage: page,
        total
      }
    });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 获取单个攻略详情
router.get('/strategies/:id', async (req, res) => {
  try {
    const strategy = await Strategy.findById(req.params.id)
      .populate('author', 'name username avatar');
    
    if (!strategy) {
      return res.status(404).json({ success: false, message: '攻略不存在' });
    }

    // 增加浏览量
    await Strategy.findByIdAndUpdate(req.params.id, { $inc: { views: 1 } });

    res.json({ success: true, data: strategy });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// ==================== 当地游相关 API ====================

// 获取当地游列表
router.get('/local-tours', async (req, res) => {
  try {
    const { page = 1, limit = 10, destination, sortBy = 'createdAt' } = req.query;
    const query = {};
    
    if (destination) query.destination = new RegExp(destination, 'i');

    const sortOptions = {};
    if (sortBy === 'price') sortOptions.price = 1;
    else if (sortBy === 'rating') sortOptions.rating = -1;
    else if (sortBy === 'popular') sortOptions.bookingCount = -1;
    else sortOptions.createdAt = -1;

    const localTours = await LocalTour.find(query)
      .sort(sortOptions)
      .limit(limit * 1)
      .skip((page - 1) * limit);

    const total = await LocalTour.countDocuments(query);

    res.json({
      success: true,
      data: {
        localTours,
        totalPages: Math.ceil(total / limit),
        currentPage: page,
        total
      }
    });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// ==================== 自由行相关 API ====================

// 获取自由行套餐列表
router.get('/free-tours', async (req, res) => {
  try {
    const { page = 1, limit = 10, destination, priceRange, duration } = req.query;
    const query = {};
    
    if (destination) query.destination = new RegExp(destination, 'i');
    if (duration) query.duration = new RegExp(duration, 'i');
    if (priceRange) {
      const [min, max] = priceRange.split('-').map(Number);
      query.price = { $gte: min, $lte: max };
    }

    const freeTours = await FreeTour.find(query)
      .sort({ isPopular: -1, createdAt: -1 })
      .limit(limit * 1)
      .skip((page - 1) * limit);

    const total = await FreeTour.countDocuments(query);

    res.json({
      success: true,
      data: {
        freeTours,
        totalPages: Math.ceil(total / limit),
        currentPage: page,
        total
      }
    });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// ==================== 跟团游相关 API ====================

// 获取跟团游列表
router.get('/group-tours', async (req, res) => {
  try {
    const { page = 1, limit = 10, destination, departureCity } = req.query;
    const query = {};
    
    if (destination) query.destination = new RegExp(destination, 'i');
    if (departureCity) query.departureCity = new RegExp(departureCity, 'i');

    const groupTours = await GroupTour.find(query)
      .sort({ isPopular: -1, createdAt: -1 })
      .limit(limit * 1)
      .skip((page - 1) * limit);

    const total = await GroupTour.countDocuments(query);

    res.json({
      success: true,
      data: {
        groupTours,
        totalPages: Math.ceil(total / limit),
        currentPage: page,
        total
      }
    });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// ==================== 酒店相关 API ====================

// 获取酒店列表
router.get('/hotels', async (req, res) => {
  try {
    const { page = 1, limit = 10, destination, starRating, priceRange } = req.query;
    const query = {};
    
    if (destination) query.destination = new RegExp(destination, 'i');
    if (starRating) query.starRating = starRating;
    if (priceRange) {
      const [min, max] = priceRange.split('-').map(Number);
      query['priceRange.min'] = { $gte: min };
      query['priceRange.max'] = { $lte: max };
    }

    const hotels = await Hotel.find(query)
      .sort({ isPopular: -1, rating: -1 })
      .limit(limit * 1)
      .skip((page - 1) * limit);

    const total = await Hotel.countDocuments(query);

    res.json({
      success: true,
      data: {
        hotels,
        totalPages: Math.ceil(total / limit),
        currentPage: page,
        total
      }
    });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// ==================== 签证相关 API ====================

// 获取签证服务列表
router.get('/visa-services', async (req, res) => {
  try {
    const { page = 1, limit = 10, country, visaType } = req.query;
    const query = {};
    
    if (country) query.country = new RegExp(country, 'i');
    if (visaType) query.visaType = new RegExp(visaType, 'i');

    const visaServices = await VisaService.find(query)
      .sort({ isPopular: -1, successRate: -1 })
      .limit(limit * 1)
      .skip((page - 1) * limit);

    const total = await VisaService.countDocuments(query);

    res.json({
      success: true,
      data: {
        visaServices,
        totalPages: Math.ceil(total / limit),
        currentPage: page,
        total
      }
    });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// ==================== 通用详情 API ====================

// 获取任何旅行服务的详情
router.get('/:type/:id', async (req, res) => {
  try {
    const { type, id } = req.params;
    let Model;
    
    switch (type) {
      case 'local-tours':
        Model = LocalTour;
        break;
      case 'free-tours':
        Model = FreeTour;
        break;
      case 'group-tours':
        Model = GroupTour;
        break;
      case 'hotels':
        Model = Hotel;
        break;
      case 'visa-services':
        Model = VisaService;
        break;
      default:
        return res.status(400).json({ success: false, message: '无效的服务类型' });
    }

    const item = await Model.findById(id);
    
    if (!item) {
      return res.status(404).json({ success: false, message: '内容不存在' });
    }

    res.json({ success: true, data: item });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// ==================== 统计 API ====================

// 获取各类服务的统计数据
router.get('/stats/overview', async (req, res) => {
  try {
    const stats = {
      strategies: await Strategy.countDocuments(),
      localTours: await LocalTour.countDocuments(),
      freeTours: await FreeTour.countDocuments(),
      groupTours: await GroupTour.countDocuments(),
      hotels: await Hotel.countDocuments(),
      visaServices: await VisaService.countDocuments()
    };

    res.json({ success: true, data: stats });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

module.exports = router; 